package com.wiscamp.ninechapters.problems.domain.models.sheets;

import com.wiscamp.ninechapters.problems.domain.ProblemsErrorCodes;
import com.wiscamp.ninechapters.problems.domain.models.problems.answers.Answer;
import com.wiscamp.ninechapters.problems.domain.models.problems.answers.MultipleOptionAnswer;
import com.wiscamp.ninechapters.problems.domain.models.problems.answers.OptionAnswer;
import com.wiscamp.ninechapters.problems.enums.AnswerTypes;
import cube.common.core.ParseUtils;
import cube.ddd.domain.Entity;
import cube.ddd.exception.ExceptionUtils;
import lombok.Data;

import java.util.Collection;
import java.util.HashMap;
import java.util.Objects;

/**
 * 答题卡明细多文本扩展
 */
@Data
public class SheetAnswer implements Entity {
    /**
     * 自动编号
     */
    private long id = 0;

    /**
     * 答题卡明细编号
     */
    private long sheetDetailId = 0;

    /**
     * 序号
     */
    private int answerIndex = 0;


    /**
     * 选项答案文本
     */
    private String optionContentText;

    /**
     * 答案文本
     */
    private String contentText;

    /**
     * 分组序号
     */
    private int answerGroupIndex = 0;

    /**
     * 是否忽略答题
     */
    private boolean skipped = false;

    /**
     * 是否正确
     */
    private boolean correct = false;

    private long correctAnswerId = 0;

    private int correctAnswerTypeId = 0;

    private int contentTypeId = 0;

    /**
     * 答案获得分数
     */
    private double gainScore = 0;

    public AnswerTypes getCorrectAnswerType() {
        return AnswerTypes.valueOf(correctAnswerTypeId);
    }


    public Collection<Long> getOptionIds() {
        return ParseUtils.parseLong(this.optionContentText, ",");
    }

    public void correctAnswer(Answer correctAnswer) {
        if (Objects.isNull(correctAnswer)) {
            ExceptionUtils.throwServiceException(ProblemsErrorCodes.SHEET_CORRECT_ANSWER_NOT_FOUND, null);
        } else {
            this.correctAnswerId = correctAnswer.getAnswerId();
            this.correctAnswerTypeId = correctAnswer.getAnswerTypeId();
        }

        if (this.skipped) {
            this.correct = false;
            return;
        }

        if (this.contentTypeId != correctAnswer.getAnswerTypeId()) {
            var data = new HashMap<String, Integer>();
            data.put("contentTypeId", this.contentTypeId);
            data.put("answerTypeId", correctAnswer.getAnswerTypeId());
            ExceptionUtils.throwServiceException(ProblemsErrorCodes.SHEET_DETAIL_ANSWER_NOT_MATCH, data);
        }

        var isCorrect = false;
        if (correctAnswer instanceof OptionAnswer || correctAnswer instanceof MultipleOptionAnswer)
        {
            isCorrect = correctAnswer.compareAnswer(this.optionContentText);
        } else {
            isCorrect = correctAnswer.compareAnswer(this.contentText);
        }
        this.setCorrect(isCorrect);
    }
}
